#include "RingQueue.hpp"
#include "Task.hpp"
#include <pthread.h>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <unistd.h>

std::string SlefName()
{
    char name[128];
    //打印线程ID，区分线程
    snprintf(name,sizeof(name),"线程[0x%x]",pthread_self());
    return name;
}

void *productorRoutine(void *args)
{
    // RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);
    while (1)
    {
        sleep(1);
        // int data = rand() % 10;
        // rq->push(data);
        // std::cout << "生产者数据：" << data << std::endl;

        int x = rand() % 10 + 1;
        int y = rand() % 5;
        Task t(x, y, option[rand() % 5], mymath);
        rq->push(t);
        std::cout <<SlefName()<< ", 生产者数据：" << t.taskToString() << std::endl;
    }
}

void *consumerRoutine(void *args)
{
    // RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);
    while (1)
    {
        // int data;
        // rq->pop(&data);
        // std::cout << "消费者数据：" << data << std::endl;

        Task t;
        rq->pop(&t);
        std::cout <<SlefName()<< ", 消费者数据：" << t() << std::endl;
    }
}

int main()
{
    srand((unsigned int)time(nullptr) ^ 0x20240503);

    // RingQueue<int> *rq = new RingQueue<int>;
    RingQueue<Task> *rq = new RingQueue<Task>();
    pthread_t p[3], c[6];
    for(int i=0;i<3;i++)
        pthread_create(p+i, nullptr, productorRoutine, rq);
    for(int i=0;i<6;i++)
        pthread_create(c+i, nullptr, consumerRoutine, rq);

    for(int i=0;i<3;i++)
        pthread_join(p[i], nullptr);
    for(int i=0;i<6;i++)
        pthread_join(c[i], nullptr);


    delete rq;

    return 0;
}

